package com.zznj.xzjc.net.rxjava;

import android.content.Intent;
import android.os.Build;
import android.util.Log;

import androidx.annotation.RequiresApi;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.zznj.xzjc.activity.LoginActivity;
import com.zznj.xzjc.application.APP;
import com.zznj.xzjc.net.entity.BaseBean;
import com.zznj.xzjc.utils.EncryptUtils;
import com.zznj.xzjc.utils.NotificationUtil;

import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * 请求接口都走此处：易涛xxx
 */
@RequiresApi(api = Build.VERSION_CODES.O)
class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final Type type;

    GsonResponseBodyConverter(Gson gson, Type type) {
        this.gson = gson;
        this.type = type;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String response = value.string();
        Log.i("response", response);
        String resultInfo = null;
        try {
            Log.i("=====Msg=======", response);
            resultInfo = EncryptUtils.aesDecrypt(response,EncryptUtils.KEY);
//            resultInfo = response;
        } catch (Exception e) {
            e.printStackTrace();
            resultInfo = null;
        }
        Log.i("=====Msg=======", resultInfo);
        BaseBean httpResult = gson.fromJson(resultInfo, BaseBean.class);
        if(httpResult.getMessage().contains("登录超时")){
            NotificationUtil no = new NotificationUtil(APP.getInstance().getApplicationContext());
            no.cancelAll();
            APP.getInstance().finishAllActivity();
            Intent intent = new Intent(APP.getInstance().getApplicationContext(),LoginActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            APP.getInstance().getApplicationContext().startActivity(intent);
            httpResult.setResult(0);
            httpResult.setMessage("登录信息失效，请重新登录！");
            throw new ApiException(httpResult);
        }
        if (!httpResult.isSuccess()) {
            throw new ApiException(httpResult);
        }
        return gson.fromJson(resultInfo, type);
    }
}
